package cn.aias.rbac.presentation.controller;

import cn.aias.rbac.application.dto.UserDTO;
import cn.aias.rbac.application.dto.UserQueryDTO;
import cn.aias.rbac.application.service.UserApplicationService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserApplicationService userService;

    public UserController(UserApplicationService userService) {
        this.userService = userService;
    }

    // 单个查询：GET /api/users/1
    @GetMapping("/{id}")
    public ResponseEntity<UserDTO> getById(@PathVariable Long id) {
        return ResponseEntity.of(Optional.ofNullable(userService.getById(id)));
    }

    // 分页查询：GET /api/users?page=0&size=10
    @GetMapping
    public ResponseEntity<Page<UserDTO>> getByPage(
            UserQueryDTO query,
            @PageableDefault(page = 0, size = 20, sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable) {
        return ResponseEntity.ok(userService.getByPage(query, pageable));
    }

    // 新增：POST /api/users
    @PostMapping
    public ResponseEntity<UserDTO> create(@RequestBody UserDTO userDTO) {
        return ResponseEntity.ok(userService.save(userDTO));
    }

    // 更新：PUT /api/users/1
    @PutMapping("/{id}")
    public ResponseEntity<UserDTO> update(
            @PathVariable Long id,
            @RequestBody UserDTO userDTO) {
        userDTO.setId(id);
        return ResponseEntity.ok(userService.save(userDTO));
    }

    // 删除：DELETE /api/users/1
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        userService.delete(id);
        return ResponseEntity.noContent().build();
    }


}
